import random
import matplotlib.pyplot as plt
import os  # 新增：导入os模块
from lk_heuristic.utils.solver_funcs import solve
from lk_heuristic.utils.plot_funcs import plot_tsp_2d


# 生成随机点
def generate_random_points(num_points, x_range, y_range):
    points = []
    for _ in range(num_points):
        x = random.randint(0, x_range)
        y = random.randint(0, y_range)
        points.append((x, y))
    return points

# 保存为TSP格式文件
def save_to_tsp(points, filename):
    with open(filename, 'w') as f:
        # 写入TSP文件头部信息
        f.write("NAME: RandomPoints\n")
        f.write("TYPE: TSP\n")
        f.write(f"DIMENSION: {len(points)}\n")
        f.write("EDGE_WEIGHT_TYPE: EUC_2D\n")
        f.write("NODE_COORD_SECTION\n")
        
        # 写入每个点的坐标
        for i, (x, y) in enumerate(points, 1):
            f.write(f"{i} {x} {y}\n")
        
        # 写入文件结束标记
        f.write("EOF\n")

# 可视化点
def visualize_points(points, title="Random Points Visualization"):
    # 创建图形并设置尺寸
    plt.figure(figsize=(12, 8))
    
    # 提取x和y坐标
    x_coords = [p[0] for p in points]
    y_coords = [p[1] for p in points]
    
    # 绘制散点图
    plt.scatter(x_coords, y_coords, c='blue', marker='o', s=50, alpha=0.7)
    
    # 添加标题和标签
    plt.title(title, fontsize=14)
    plt.xlabel('X Coordinate', fontsize=12)
    plt.ylabel('Y Coordinate', fontsize=12)
    
    # 添加网格
    plt.grid(True, linestyle='--', alpha=0.6)
    
    # 显示图形
    plt.show()



if __name__ == "__main__":
    # 参数设置
    NUM_POINTS = 20
    X_RANGE = 50000
    Y_RANGE = 700000
    new_data = False
    
    current_dir = os.path.dirname(os.path.abspath(__file__))
        # 新增：设置TSP文件路径为当前目录下的random_points.tsp
    tsp_filename = os.path.join(current_dir, "random_points.tsp")
    if new_data:
    # 新增：获取当前脚本所在目录
        
        
        # 生成并可视化点
        random_points = generate_random_points(NUM_POINTS, X_RANGE, Y_RANGE)
        visualize_points(random_points, f"{NUM_POINTS} Random Points in {X_RANGE}x{Y_RANGE} Area")

        # 打印点坐标
        print("Generated Points:")
        for i, (x, y) in enumerate(random_points, 1):
            print(f"Point {i}: ({x}, {y})")
        
        # 保存为TSP格式
        # 修改：使用新的tsp_filename变量
        save_to_tsp(random_points, tsp_filename)
        print(f"Points saved to {tsp_filename}")

    solve(tsp_file=tsp_filename, solution_method="lk1_improve", runs=50, backtracking=(5, 5), reduction_level=4, reduction_cycle=4, tour_type="cycle", file_name="", logging_level=20)
